import subprocess

from src.BaseThread import BaseThread
from src.FrameParser import FrameParser


class FileMonitor(BaseThread):
    CMD = '''
        ls ../asset/ | xargs -i cat ../asset/{}
    '''

    def __init__(self):
        BaseThread.__init__(self, "FileMonitor", 1)
        self.process = None
        self.frame_parser = FrameParser()

    def pre_job(self):
        self.process = subprocess.Popen(self.CMD,
                                        bufsize=1,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        shell=True)

    def after_job(self):
        self.process = None

    def real_job(self):
        line = self.process.stdout.readline().decode('utf-8')
        if len(line) > 0:
            self.frame_parser.parse_line(line[:-1])
            return True
        elif line == '':
            self.print('EOF')
            return False
